package com.example.postman.restful.service.impl;

import com.example.postman.exception.ValidattionException;
import com.example.postman.restful.entity.PostMan;
import com.example.postman.restful.entity.User;
import com.example.postman.restful.mapper.PostManMapper;
import com.example.postman.restful.service.PostManService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 类
 * 创建时间：2022/3/14 17:33
 *
 * @author gejin
 */
@Service
public class PostManServiceImpl implements PostManService {
    @Autowired
    private PostManMapper postManMapper;

    @Override
    public int add(PostMan postMan) {
        return postManMapper.add(postMan);
    }

    @Override
    public PostMan getPostManById(String postId) {
        return postManMapper.getPostManById(postId);
    }

    @Override
    public int updatePostMan(PostMan postMan) {
        return postManMapper.updatePostMan(postMan);
    }

    @Override
    public int deletePostManById(String postId) {
        return postManMapper.deletePostManById(postId);
    }

    /**
     * 注册用户
     *
     * @param userName
     * @param phone
     * @throws ValidattionException
     */
    public User registerUser(String userName, String phone) throws ValidattionException {
        if (userName == null || userName.length() == 0) {
            throw new ValidattionException("用户名不能为空");
        }
        if (phone == null || isValidate(phone)) {
            throw new ValidattionException("手机号格式不正确！");
        }
        String areaCode = postManMapper.getAreaCode(phone);
        String oprateCode = postManMapper.getOprateCode(phone);
        User user;
        try {
            String rep = postManMapper.findRep(areaCode, oprateCode);
            user = postManMapper.save(areaCode, oprateCode, rep);
        } catch (ValidattionException exception) {
            throw new ValidattionException("存在sqlException");
        }
        return user;
    }

    /**
     * 验证手机号
     *
     * @param phone
     * @return boolean
     */
    private boolean isValidate(String phone) {
        String pattern = "^1[345678]\\d{9}$";
        boolean flag = phone.matches(pattern);
        return flag;
    }
}
